package com.sms.fileupload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ReplyReportServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		HttpSession session = request.getSession();
		String role = (String)session.getAttribute("role");
		
		// 返回ajax的信息
		String msg = "";
		List<Map> appendFile = null;

		// Create a factory for disk-based file items
		DiskFileItemFactory disk = new DiskFileItemFactory();
		// 当上传文件太大时，因为虚拟机能使用的内存是有限的，所以此时要通过临时文件来实现上传文件的保存
		// 此方法是设置是否使用临时文件的临界值（单位：字节）
		disk.setSizeThreshold(1024 * 5);// 设置上传缓冲区容量为5k

		String servletPath = this.getServletContext().getRealPath("/");// 获得服务器所在地址
		String tempFile = "tempFile";
		String saveFile = "uploadFile";
		String tempPath = servletPath + tempFile;//临时文件路径
		String savePath = servletPath + saveFile;//存放文件实际路径
		
		File tfile = new File(tempPath);
		if (!tfile.exists()) {
			tfile.mkdirs();
		}
		
		File sfile = new File(savePath);
		if (!sfile.exists()) {
			sfile.mkdirs();
		}
		disk.setRepository(tfile);

		// 创建能够解析上传文件的二进制流的类
		ServletFileUpload sfu = new ServletFileUpload(disk);
		long maxsize = 1024 * 1024 * 100;
		sfu.setSizeMax(maxsize);// 限制最大上传容量为100M

		List<FileItem> list = null;
		try {
			list = sfu.parseRequest(request);
		} catch (FileUploadException e) {
			msg = "error";
		}

		Iterator it = null;

		try {
			it = list.iterator();
		} catch (NullPointerException e) {
			out.println("<script language='javascript'>");
			out.println("alert('不支持你所上传文件的类型')");
			out.println("</script>");
			msg = "error";
		}

		if (it != null) {
			String content = "";
			String type = "";
			int rootID = 0;
			int pid = 0;
			int taskID = 0;
			String fromID = "";
			String toID = "";
			appendFile = new ArrayList<Map>();
			while (it.hasNext()) {
				FileItem fileItem = (FileItem) it.next();

				if (fileItem.isFormField()) {// 为表单域
					String name = fileItem.getFieldName();
					String value = new String(fileItem.getString().getBytes("ISO-8859-1"), "utf-8");
					value.replace("\r\n", "<br>");
			    	
					if (name.equals("content")) {
						content = value;
					} else if (name.equals("type")) {
						type = value;
					} else if (name.equals("rootid")) {
						rootID = Integer.parseInt(value);
					} else if(name.equals("pid")) {
						pid = Integer.parseInt(value);
					} else if (name.equals("taskid")) {
						taskID = Integer.parseInt(value);
					} else if(name.equals("fromid")) {
						fromID = value;
					} else if(name.equals("toid")) {
						toID = value;
					}
					
				} else { // 为文件上传域
					String locPath = fileItem.getName();// 上传文件所在的本机的绝对路径
					if (!locPath.equals("")) {// 上传文件路径不为空
						Boolean isSuccess = false;
						
						// 获得上传文件的文件名
						int index = locPath.lastIndexOf("\\");
						String fileName = locPath.substring(index + 1);//文件的实际文件名，下载时候设置头信息用
						
						String saveName = "";//保存在服务器上的文件名，由日期+随机数+后缀组成
						SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
						saveName += sdf.format(new java.util.Date());
						
						for(int i=0; i<6; i++) {//得到6位10以内的随机数
							Random random = new Random();
							int r = random.nextInt(10);
							saveName += r;
						}
						
						//得到有后缀名的用来保存在服务器上的整个文件名
						index = locPath.lastIndexOf(".");
						saveName += locPath.substring(index);
						

						//long filesize = fileItem.getSize();
					

						String serverPath = savePath + "\\" + saveName;// 文件上传到服务器端的绝对路径
						File f = new File(serverPath);
						
						/*try {
							fileItem.write(f);
						} catch (Exception e) {
							e.printStackTrace();
						}*/
						
						FileOutputStream fos = new FileOutputStream(f);

						if (fileItem.isInMemory()) {
							try {
								fos.write(fileItem.get());
								isSuccess = true;
							} catch (IOException e) {
								msg = "error";
							} finally {
								fos.close();
							}
						} else {
							InputStream is = null;
							try {
								is = fileItem.getInputStream();
								int i = -1;// 文件是否读完标志
								byte[] b = new byte[1024];
								i = is.read(b);
								while (i > 0) {
									fos.write(b, 0, i);
									i = is.read(b);
								}
								isSuccess = true;
							} catch (IOException e) {
								msg = "error";
							} finally {
								is.close();
								fos.flush();
								fos.close();
							}
						}
						
						
						if (isSuccess && !msg.equals("error")) {
							
							Map<String, String> map = new HashMap<String, String>();
							map.put("fileName", fileName);
							map.put("saveName", saveName);
							appendFile.add(map);
						} else {
							msg = "error";
						}
					}//上传为文件路径不为空结束

				}//上传 为文本域结束
			}//while结束
			
			//插入数据库关于新项目的信息
			boolean isSuccess = new NewReport().insertData(type, rootID, pid, taskID, fromID, toID, content, appendFile);
			if(isSuccess) {
				msg = "ok";
			} else {
				msg = "error";
			}
		}
		
		msg.replace("/rn/g", "");
		if(msg.equals("ok")) {
			out.println("<script language='javascript'>");
			out.println("parent.callback('ok')"); 
			out.println("</script>");
		} else {
			out.println("<script language='javascript'>");
			out.println("parent.callback('error')");   
			out.println("</script>");
		}
		
//		out.print(msg);
		out.flush();
		out.close();
    	
		
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}


}
